Lecture Lab 9

Leon Eyrich Jessen

Creating a Simple Shiny App

But… What is Shiny? …and how does it relate to a package?

What if you wanted to “share your code” with someone who don’t know how to code? 🤔

  • A package is an ordered and documented collection of functions

  • A Shiny app is an interface on top of an ordered and documented collection of functions

General Idea is to…

  • Shiny enables writing powerful interactive web apps in R, thereby:
    • Connecting non-data literate people with data
    • Automating time consuming tasks
    • Exhibiting data to relevant stakeholders
    • Generating value by facilitating extraction of insights




Seeing is believing

Hello Shiny!

# Load the Shiny library
library("shiny")

# Define the User Interface (Frontend)
ui <- fluidPage(
  titlePanel("Hello Shiny!"),
  sidebarLayout(
    sidebarPanel(
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),
    mainPanel(
      plotOutput(outputId = "distPlot")
    )
  )
)

# Define the Server (Backend)
server <- function(input, output) {
  output$distPlot <- renderPlot({
    x <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = "#75AADB", border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")
  })
}

# Launch the shiny app
shinyApp(ui = ui, server = server)

Hello Shiny!

# Load the Shiny library
library("shiny")

# Define the User Interface (Frontend)
ui <- fluidPage(
  titlePanel("Hello Shiny!"),
  sidebarLayout(
    sidebarPanel(
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),
    mainPanel(
      plotOutput(outputId = "distPlot")
    )
  )
)

# Define the Server (Backend)
server <- function(input, output) {
  output$distPlot <- renderPlot({
    x <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = "#75AADB", border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")
  })
}

# Launch the shiny app
shinyApp(ui = ui, server = server)

Hello Shiny!

  • Frontend, the user interface
    • This is where the user interacts with your app
    • Chooses arguments to function parameters
    • Choices are “requests”
  • Backend, the server
    • This is where the computations are made in response to the user’s choices
    • Chosen arguments are passed to function parameters, producing an output
    • The output is the “response”

This frontend-to-backend continous communication is key!